//
//  iengageAppDelegate.m
//  iengage
//
//  Created by Luis Ziliani on 2/9/09.
//  Copyright Manas 2009. All rights reserved.
//

#import "iengageAppDelegate.h"
#import "GroupViewController.h"
#import "Util.h"
#import "FileDownload.h"

#define PreferenceNameKey		@"name_preference"
#define PreferencePasswordKey	@"password_preference"
#define PreferenceServerKey		@"server_preference"

#define GroupServiceName		@"getGroups"

@interface IEngageAppDelegate (Private) 
- (BOOL) loadApplicationDefaults;

@end

@implementation IEngageAppDelegate (Private) 

- (BOOL) loadApplicationDefaults {
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    [self setCurrentUser:[defaults stringForKey:PreferenceNameKey]]; 
	[self setUserPassword:[defaults stringForKey:PreferencePasswordKey]]; 
	[self setServerURL:[defaults stringForKey:PreferenceServerKey]]; 
	
	BOOL showAlert = [NSString isNullOrEmpty: currentUser] || 
					[NSString isNullOrEmpty: userPassword] ||
					[NSString isNullOrEmpty: serverURL]; 
	
	if (showAlert) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"User information missing" message:   @"In order to use this application, you have to provide the settings needded to work. Please go to \"Settings -> iengage\" and fill all the fields."  
													   delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
		[alert show];
		[alert release];
		return FALSE;
	}

	return TRUE;
}

@end


@implementation IEngageAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize users;
@synthesize currentUser;
@synthesize userPassword;
@synthesize serverURL;
@synthesize appState;


- (void)applicationDidFinishLaunching:(UIApplication *)application {
	appState = [[AppStateHandler alloc] init];
	[appState restoreStateIfPossible];
	
	if (![self loadApplicationDefaults]) {
		return ;
	}
	
	GroupViewController *groupController = [[GroupViewController alloc] init];

	self.navigationController = [[UINavigationController alloc] initWithRootViewController:groupController];
	self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.45 green:0.45 blue:0.45 alpha:1.0];
	groupController.navigationController = navigationController;		
	[groupController release];
	
	// Configure and show the window
	[window addSubview:[navigationController view]];
	[window makeKeyAndVisible];	
}


- (void)applicationWillTerminate:(UIApplication *)application {
	[appState saveState];
}


- (void)dealloc {
	[navigationController release];
	[window release];
	[users release];
	[currentUser release];
	[userPassword release];
	[serverURL release];
	[super dealloc];
}

- (NSString *) groupServiceURL {
	NSMutableString * url = [NSMutableString stringWithString:[self serverURL]];
	[url appendString:@"/"];
	[url appendString:GroupServiceName];
	[url autorelease];
	return url;
}

@end
